package cn.qn.framwork.security;

import cn.qn.enums.JwtAuthEnum;
import cn.qn.moudle.security.Permission;
import cn.qn.moudle.security.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * Created by sang on 2017/12/28.
 */
@Component
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {


    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private MemberAccountService memberAccountService;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation)o;
        String requestUrl = filterInvocation.getRequestUrl();
        if(IgnorePathConfig.ignoreRequest(filterInvocation.getRequest())){
            return null;
        }
        String token = filterInvocation.getRequest().getHeader(JwtAuthEnum.AUTHORIZATION.getCode()).replace(JwtAuthEnum.AUTH_HEADER.getCode(),"");
        List<Permission> permissions = memberAccountService.findAllPermission();
        for (Permission permission : permissions) {
            if (null!=permission.getPermission() && antPathMatcher.match(permission.getPermission(), requestUrl)) {
                List<Role> roles = memberAccountService.findRolesByPermissionId(permission.getId());
                int size = roles.size();
                if(size<1){
                    throw new AccessDeniedException("["+permission.getName()+"]权限不足，请联系管理员!");
                }
                String[] values = new String[size];
                for (int i = 0; i < size; i++) {
                    values[i] = roles.get(i).getName();
                }
                return SecurityConfig.createList(values);
            }
        }
        //没有匹配上的资源，都是登录访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
